/**
 * Copyright (c) 2020 - present, Inspur Genersoft Co., Ltd.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *       http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
import { computed, ComputedRef, Ref, ref, SetupContext, watch } from 'vue';
import { ButtonEditProps } from '../button-edit.props';
import { UseClear, UseTextBox } from './types';

export function useClear(
    props: ButtonEditProps,
    context: SetupContext,
    modelValue: Ref<string>,
    hasFocusedTextBox: ComputedRef<boolean>,
    displayText: Ref<string>,
    useTextBoxCompostion: UseTextBox
): UseClear {
    const showClearButton = ref(false);
    const enableClearButton = computed(() => props.enableClear && !props.readonly && !props.disable);
    const { changeTextBoxValue } = useTextBoxCompostion;

    function toggleClearIcon(isShow: boolean) {
        showClearButton.value = isShow;
    }

    watch(displayText, () => {
        if (hasFocusedTextBox.value) {
            toggleClearIcon(!!displayText.value);
        } else {
            toggleClearIcon(false);
        }
    });

    function onClearValue($event: Event) {
        const flag1 = !props.readonly && !props.disable && props.editable;
        const flag2 = !props.editable;
        $event.stopPropagation();
        if (flag1 || flag2) {
            changeTextBoxValue('', false);
            toggleClearIcon(!showClearButton.value);
            context.emit('clear');
        }
    }

    function onMouseEnterTextBox($event: Event) {
        if (!enableClearButton.value) {
            return;
        }
        if (!modelValue.value) {
            toggleClearIcon(false);
            return;
        }
        if ((!props.editable || !props.readonly) && !props.disable) {
            toggleClearIcon(true);
        }
    }

    function onMouseLeaveTextBox($event: Event) {
        if (!enableClearButton.value) {
            return;
        }
        toggleClearIcon(false);
    }

    return {
        enableClearButton,
        showClearButton,
        onClearValue,
        onMouseEnterTextBox,
        onMouseLeaveTextBox
    };
}
